// Coze API服务
const axios = require("axios");

/**
 * 调用Coze API的工作流
 * @param {string} workflowId 工作流ID
 * @param {object} parameters 参数
 * @returns {Promise<object>} API响应
 */
async function callCozeWorkflow(workflowId, parameters = {}) {
	try {
		const response = await axios({
			method: "post",
			url: `${process.env.COZE_BASE_URL}/v1/workflow/run`,
			headers: {
				"Content-Type": "application/json",
				Authorization: `Bearer ${process.env.COZE_TOKEN}`,
			},
			data: {
				workflow_id: workflowId,
				parameters: parameters,
				app_id: "7488577857250328639",
			},
		});

		if (response.data && response.data.code === 0) {
			// 解析返回的JSON字符串数据
			const dataString = response.data.data;
			if (dataString) {
				try {
					const parsedData = JSON.parse(dataString);
					return {
						success: true,
						data: parsedData.data || parsedData,
					};
				} catch (parseError) {
					console.error("解析Coze返回数据失败:", parseError);
					return {
						success: false,
						error: "解析返回数据失败",
					};
				}
			}
		}

		return {
			success: false,
			error: response.data.msg || "调用Coze API失败",
		};
	} catch (error) {
		console.error("调用Coze API出错:", error);
		return {
			success: false,
			error: error.message || "网络请求失败",
		};
	}
}

/**
 * 获取今日古诗
 * @param {object} options 查询选项 {keyword, tags, writer}
 * @returns {Promise<object>} 今日古诗数据
 */
async function getDailyPoem(options = {}) {
	const parameters = {
		keyword: options.keyword || "",
		tags: options.tags || "",
		writer: options.writer || "",
	};
	return await callCozeWorkflow(
		process.env.COZE_DAILY_POEM_WORKFLOW_ID,
		parameters
	);
}

/**
 * 搜索古诗
 * @param {object} options 搜索选项 {keyword, tags, writer}
 * @returns {Promise<object>} 搜索结果
 */
async function searchPoems(options = {}) {
	const parameters = {
		keyword: options.keyword || "",
		tags: options.tags || "",
		writer: options.writer || "",
	};

	return await callCozeWorkflow(
		process.env.COZE_SEARCH_POEM_WORKFLOW_ID,
		parameters
	);
}

/**
 * 获取古诗插图
 * @param {string} poem 古诗内容
 * @returns {Promise<object>} 插图数据
 */
async function getPoemIllustration(poem) {
	const parameters = {
		poem: poem,
	};

	return await callCozeWorkflow(
		process.env.COZE_POEM_ILLUSTRATION_WORKFLOW_ID,
		parameters
	);
}

module.exports = {
	getDailyPoem,
	searchPoems,
	getPoemIllustration,
};
